package cn.wonderland.controller;

import cn.wonderland.domain.Device;
import cn.wonderland.service.DeviceService;
import cn.wonderland.util.JSONResult;
import cn.wonderland.vo.DeviceBuildVo;
import cn.wonderland.vo.DeviceVo;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import javafx.util.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    /*
     * 新增设备
     * */
    @PostMapping("/add")
    public JSONResult<Device> addDevice(@RequestBody Device device) {
        if (device.getType() == null || device.getName() == null || device.getBuildId() == null || device.getFloorId() == null) {
            return JSONResult.<Device>builder().message("参数不能为空！").data(null).code("500").success(false).build();
        } else {
            deviceService.addDevice(device);
            return JSONResult.<Device>builder().message("请求成功").data(null).code("200").success(true).build();
        }
    }

    /*
     * 根据设备id查询设备信息
     * getDeviceInfoById
     * */
    @GetMapping("/getDeviceInfoById")
    @SentinelResource(
            value = "service-device-getDeviceInfoById",
            blockHandler = "limitBlockHandler",
            fallback = "fuseDegradation")
    public JSONResult<DeviceVo> getDeviceInfoById(@RequestParam("id") Integer id) {
        DeviceVo device = deviceService.getDeviceInfoById(id);
//        int a = 1/0; // 测试熔断
        return JSONResult.<DeviceVo>builder().success(true).code("200").data(device).message("请求成功").build();

    }


    /*
    根据设备id查询设备信息流控 5分
    根据设备id查询设备信息降级  5分
     */
    public JSONResult<DeviceVo> limitBlockHandler(@RequestParam("id") Integer id, BlockException be) {
        be.printStackTrace();
        return JSONResult.<DeviceVo>builder().success(false).code("500")
                .data(null).message("流控了").build();
    }

    public JSONResult<DeviceVo> fuseDegradation(@RequestParam("id") Integer id, Throwable e) {
        e.printStackTrace();
        return JSONResult.<DeviceVo>builder().success(false).code("500")
                .data(null).message("熔断了").build();
    }


    /*
     * 根据楼宇id查询设备详情
     */
    @GetMapping("/getDeviceByBuildId")
    public List<DeviceBuildVo> getDeviceByBuildId(@RequestParam("id") Integer id) {
        return deviceService.getDeviceByBuildId(id);
    }


    /*
     * 根据设备类型获取所有设备信息
     */
    @GetMapping("/getDeviceByType")
    public List<Device> getDeviceByType(@RequestParam("type") Integer type) {
        return deviceService.getDeviceByType(type);
    }

}
